package Middleware

import (
	"baize/app/Middleware/Jwtc"
	"net/http"
	"strings"

	"baize/app/Models"
	"github.com/gin-gonic/gin"
	"log"
)

func JWTAuth() gin.HandlerFunc {
	return func(c *gin.Context) {
		accessToken := c.Request.Header.Get("Authorization")
		if accessToken == "" {
			c.JSON(http.StatusOK, gin.H{
				"code":    2003,
				"status":  false,
				"message": "请求头中的 Authorization 为空",
			})
			c.Abort()
			return
		}

		parts := strings.SplitN(accessToken, " ", 2)
		if !(len(parts) == 2 && parts[0] == "Bearer") {
			c.JSON(http.StatusOK, gin.H{
				"code":    2004,
				"status":  false,
				"message": "请求头中的 Authorization 格式错误, 使用 Bearer",
			})
			//阻止调用后续的函数
			c.Abort()
			return
		}

		data := &Jwtc.ClaimsData{}
		sign := parts[1]
		claims, err := Jwtc.Verify(sign)
		if err != nil {
			// token 失效的报错日志
			log.Println(err)
			c.JSON(http.StatusForbidden, gin.H{
				"code":    2005,
				"status":  false,
				"message": "身份认证失败",
			})
			c.Abort()
			return
		}
		// 数据库检验 token 中的用户是否存在
		var json_users Models.Users
		_, err = json_users.FindUser(claims.Username)
		if err != nil {
			log.Println(err)
			c.JSON(403, gin.H{
				"code":    2005,
				"status":  false,
				"message": "身份认证失败",
			})
			c.Abort()
			return
		}
		c.Set("authInfo", data)
		c.Next()
	}
}
